package com.zxyankh.leetcode.question.chinese;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 给定一个没有重复数字的序列，返回其所有可能的全排列。
 * <p>
 * 示例:
 * <p>
 * 输入: [1,2,3]
 * 输出:
 * [
 * [1,2,3],
 * [1,3,2],
 * [2,1,3],
 * [2,3,1],
 * [3,1,2],
 * [3,2,1]
 * ]
 *
 * @author zxyAnkh
 */
public class No46 {

    public List<List<Integer>> permute(int[] nums) {
        List<List<Integer>> result = new ArrayList<>(factorial(nums.length));

        List<Integer> list = new ArrayList<>(nums.length);
        for (int num : nums) {
            list.add(num);
        }

        int n = nums.length;
        backTrack(n, list, result, 0);

        return result;
    }

    private void backTrack(int n, List<Integer> list, List<List<Integer>> result, int first) {
        if (first == n) {
            result.add(new ArrayList<>(list));
        }
        for (int i = first; i < n; i++) {
            Collections.swap(list, first, i);
            backTrack(n, list, result, first + 1);
            Collections.swap(list, first, i);
        }
    }

    private int factorial(int number) {
        if (number <= 1) {
            return 1;
        } else {
            return number * factorial(number - 1);
        }
    }

}
